#-*- coding:utf-8 -*-

import threading
import time

class _timeThread():
    """ """
    timeList =  [];
    timeThread = None
    timeRunFlag = False;
    @staticmethod
    def addTool(method,times,func,*args):
        """
        """
        tmID = _timeFunc(times,func,*args)
        if method == 2:
            tmID.Interval()
        _timeThread.timeList.append(tmID)
        if not _timeThread.timeThread or not _timeThread.timeThread.isAlive():# 
            _timeThread.timeThread = threading.Thread(target=_timeThread.run,args=());
            _timeThread.timeThread.start();
        #elif  not _timeThread.timeThread.isAlive():
        #    _timeThread.timeThread.run()
            
        return tmID;
        
    @staticmethod
    def removeTool(tmID):
        """ """
        if tmID in _timeThread.timeList:
            _timeThread.timeList.remove(tmID);
        
    @staticmethod
    def run(*arg):
        _timeThread.timeRunFlag = True
        while _timeThread.timeRunFlag and len(_timeThread.timeList)>=1:
            tmList = []
            for tmID in _timeThread.timeList:
                if tmID.update():
                    tmList.append(tmID);
            for tmID in tmList:
                if tmID.isRemove():
                    _timeThread.removeTool(tmID)
                tmID.func();
            time.sleep(1);
        
    @staticmethod
    def stop():
        _timeThread.timeRunFlag = False; 
        
class _timeFunc(object):
    """ """
    def __init__(self,times,func,*args):
        """ """
        self._times  = times
        self._funcs   = func
        self._args   = args
        self._secs   =   0
        self._not    = False
        
    def Interval(self):
        """ """
        self._not    = True
        
    def update(self):
        """ """
        self._secs += 1
        if self._secs >= self._times:
            if self._not:
                self._secs = 0
            return True
            
    def isRemove(self):
        """ """
        return not self._not;
        
    def func(self):
        """ """
        a = threading.Thread(target = self._funcs,args=self._args)
        return a.start()


def setTimeOut(times,func,*args):
    """ """
    return _timeThread.addTool(1,times,func,*args)
    
def setIntreval(times,func,*args):
    """ """
    return _timeThread.addTool(2,times,func,*args)

def removeTimer(timer):
    """ """
    _timeThread.removeTool(timer);
    
def stopTimer():
    """ """
    _timeThread.stop()
    
